package com.baidu.web;

import com.baidu.pojo.CarBean;
import com.baidu.pojo.CustomerBean;
import com.baidu.pojo.GoodsBean;
import com.baidu.pojo.OrderBean;
import com.baidu.service.GoodsWebService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 创作时间：2019/11/6 9:59
 * 作者：李增强
 */
@Controller
public class GoodsWeb {

    @Resource
    private GoodsWebService goodsWebService;

    @RequestMapping("/getOrderList")
    public String getOrderList(HttpServletRequest request,Model model){
        CustomerBean cb = (CustomerBean)request.getSession().getAttribute("cb");
        List<OrderBean> list = goodsWebService.getOrderListByCid(cb.getId());
        model.addAttribute("list", list);
        return "order_list";
    }

    @RequestMapping("/toPayGoods")
    public String toPayGoods(HttpServletRequest request,Integer[] gids){
        CustomerBean cb = (CustomerBean)request.getSession().getAttribute("cb");
        /**
         * 过来支付了，
         * 用户需要添加收货地址，要是不想做那块，直接生成订单。去支付
         * 生成订单就把购物车里面已经在订单里面的商品删除，
         *
         * 订单表：订单号:用户id，总价，订单状态，（-1，已取消，0，未支付，1，已支付，2，已发货，3，完成）
         * 订单详情表：id，商品id，购买数量。订单号
         *
         */
        goodsWebService.saveGoodsOrder(cb.getId(),gids);

        return "redirect:getOrderList.do";
    }


    @ResponseBody
    @RequestMapping("/getWebLogin")
    public void getWebLogin(String cname,String pwd,HttpServletRequest request,HttpServletResponse response){
        CustomerBean cb = goodsWebService.getWebLogin(cname,pwd);
        try {
            if(cb!=null){

                /**
                 * 登录成功后把cookie里面的值拿出来，放到数据库中去
                 */
                Cookie[] cookies = request.getCookies();
                if(cookies!=null){
                    List<CarBean> clist = new ArrayList<>();
                    for (Cookie cookie : cookies) {
                        if(!"JSESSIONID".equals(cookie.getName())){
                            String value = cookie.getValue();
                            String name = cookie.getName();
                            CarBean car = new CarBean();
                            car.setCid(cb.getId());
                            car.setCount(Integer.valueOf(value));
                            car.setGid(Integer.valueOf(name));
                            clist.add(car);
                        }
                    }
                    goodsWebService.saveCarInfo(clist);
                }


                request.getSession().setAttribute("cb", cb);
                response.getWriter().write("ok");
            }else{
                response.getWriter().write("no");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @RequestMapping("/getLoginInfo")
    @ResponseBody
    public void getLoginInfo(HttpServletRequest request,HttpServletResponse response){
        CustomerBean cb = (CustomerBean)request.getSession().getAttribute("cb");
        String msg="no";
        if(cb!=null){
            msg="ok";
        }
        try {
            response.getWriter().write(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 修改购物车中商品的数量，用户没有登录的时候
     */
    @RequestMapping("/updateCarGoodsCount")
    @ResponseBody
    public void updateCarGoodsCount(HttpServletResponse response,Integer gid,Integer count,HttpServletRequest request){
        CustomerBean cb = (CustomerBean)request.getSession().getAttribute("cb");
        if(cb!=null){
            goodsWebService.updateGoodsCount(cb.getId(),gid,count);
        }else{
            Cookie ck = new Cookie(gid.toString(), count.toString());
            response.addCookie(ck);
        }
        try {
            response.getWriter().write("ok");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    /**
     * 没有登录的情况下去购物车
     */
    @RequestMapping("/toGetShopCarInfo")
    public String toGetShopCarInfo(HttpServletRequest request,Model model){
        CustomerBean cb = (CustomerBean)request.getSession().getAttribute("cb");
        List<GoodsBean> list = new  ArrayList();
        if(cb!=null){
            list = goodsWebService.getCarListById(cb.getId());
        }else{
            Cookie[] cookies = request.getCookies();
            /**
             * cookie里面的对象拿到了，但是我们放进去1个，拿出来两个，多了一个
             * JSEESIONID:这是session的id，多个页面，都在没有登录的情况下访问服务器，服务器，怎么知道的是那个页面来的
             * 通过sessionid。session的id默认是存在cookie里面的。就算我们不给cookie里面存放东西，它里面也有seesionid在里面
             * 但是有时候，我们在第一次访问的时候，会发现，我们的url后面多了好多东西，就是seesion的id，为什么？因为浏览器或者客户
             * 把浏览器的cookie给禁用了，到了服务器，怎么区分，只能把seesionid通过url带过去，专业术语  url重写
             */
            if(cookies!=null){
                for (Cookie cookie : cookies) {
                    if(!"JSESSIONID".equals(cookie.getName())){
                        String value = cookie.getValue();
                        String name = cookie.getName();
                        GoodsBean gb = goodsWebService.getGoodsWebByGid(Integer.valueOf(name));
                        gb.setCount(Integer.valueOf(value));
                        list.add(gb);
                    }
                }

            }
        }
        model.addAttribute("list", list);
        return "car_list";
    }


    /**
     *把用户选择好的商品，存入购物车
     *
     */
    @RequestMapping("/toAddGoodsToCar")
    public String toAddGoodsToCar(Integer gid, HttpServletRequest request, HttpServletResponse response,Model model){
        /**
         * 判断用户有没有登录，登录了的话，需要把购物车放到数据库
         * 没有登录的话，只能放到cookie里面了。
         * 换一个浏览器就没有了
         */
        CustomerBean cb = (CustomerBean)request.getSession().getAttribute("cb");
        GoodsBean gb = goodsWebService.getGoodsWebByGid(gid);
        if(cb==null){
            Cookie ck = new Cookie(gid.toString(), "1");
            response.addCookie(ck);
        }else{
            CarBean car = new CarBean();
            car.setCid(cb.getId());
            car.setGid(gid);
            car.setCount(1);
            goodsWebService.saveGoodsToCar(car);
        }
        model.addAttribute("gb", gb);
        return "add_success";
    }

    @RequestMapping("/toGetGoodsInfo")
    public String toGetGoodsInfo(Integer gid,Model model){
        GoodsBean gb =goodsWebService.getGoodsWebByGid(gid);
        model.addAttribute("gb", gb);
        return "goods_info";
    }

    @RequestMapping("/getGoodsWebList")
    public String getGoodsWebList(Model model){
        List<GoodsBean> list = goodsWebService.getGoodsWebList();
        model.addAttribute("list", list);
        return "index";
    }
}
